package com.itouch.bracelet.activity;

import java.text.DecimalFormat;
import java.util.ArrayList;

import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.itouch.bracelet.R;
import com.itouch.bracelet.bean.Child;
import com.itouch.bracelet.bean.LoginUser;
import com.itouch.bracelet.bean.MedAndLacPercent;
import com.itouch.bracelet.bean.MedAndLacPercentResult;
import com.itouch.bracelet.bean.MedPercentAndSport;
import com.itouch.bracelet.bean.MedPercentAndSportResult;
import com.itouch.bracelet.cache.UserCache;
import com.itouch.bracelet.diseaseinfo.Constants;
import com.itouch.util.LoadingDialog;
import com.itouch.widget.circleprogress.DonutProgress;
import com.itouch.widget.holographlibrary.Line;
import com.itouch.widget.holographlibrary.LineGraph;
import com.itouch.widget.holographlibrary.LinePoint;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;

public class MainRightFragment extends Fragment implements OnClickListener {
	private ImageView medication;
	private ImageView feed_info;
	private TextView child_regiser;
	private ImageView avat_change;
	private ImageView avat_main;
	private TextView child_name;
	private TextView child_device;
	private ImageLoader imageLoader = ImageLoader.getInstance();
	private DisplayImageOptions options;
	private DonutProgress lactation_progress;
	private DonutProgress medecent_progress;
	private LineGraph li;
	private LoadingDialog loadingDialog;
	private TextView nextLacDate;
	private TextView nextMedDate;
	private TextView c_tem;
	private DecimalFormat df;

	private LinearLayout headll;//头像layout
	
	private LinearLayout top_layout;
	private LinearLayout center_layout;
	

	private LinearLayout childtemp;
	private LinearLayout childstep;
	
	private TextView c_step;
	
	
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragmen_mainright, null);
	}

	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initViews();
	}

	private void initViews() {
		df = new DecimalFormat("##.#");
		options = new DisplayImageOptions.Builder()
				.showImageForEmptyUri(R.drawable.c_default_avatar)
				.showImageOnFail(R.drawable.c_default_avatar)
				.resetViewBeforeLoading(true).cacheOnDisc(true)
				.imageScaleType(ImageScaleType.EXACTLY)
				.bitmapConfig(Bitmap.Config.RGB_565).considerExifParams(true)
				.displayer(new FadeInBitmapDisplayer(300)).build();

		headll=(LinearLayout) getActivity().findViewById(R.id.headll);
		headll.setOnClickListener(this);
		
		top_layout = (LinearLayout) getActivity().findViewById(R.id.top_layout);
		center_layout = (LinearLayout) getActivity().findViewById(
				R.id.center_layout);

		lactation_progress = (DonutProgress) getActivity().findViewById(
				R.id.lactation_progress);
		medecent_progress = (DonutProgress) getActivity().findViewById(
				R.id.medecent_progress);

		c_tem = (TextView) getActivity().findViewById(R.id.c_tem);
		child_name = (TextView) getActivity().findViewById(R.id.child_name);
		child_device = (TextView) getActivity().findViewById(R.id.child_device);

		nextMedDate = (TextView) getActivity().findViewById(R.id.nextMedDate);
		nextLacDate = (TextView) getActivity().findViewById(R.id.nextLacDate);

		child_regiser = (TextView) getActivity().findViewById(
				R.id.child_regiser);
		child_regiser.setOnClickListener(this);
		medication = (ImageView) getActivity().findViewById(R.id.medication_c);
		medication.setOnClickListener(this);

		avat_change = (ImageView) getActivity().findViewById(R.id.avat_change);
		avat_change.setOnClickListener(this);

		avat_main = (ImageView) getActivity().findViewById(R.id.avat_main);
		avat_main.setOnClickListener(this);

		feed_info = (ImageView) getActivity().findViewById(R.id.feed_info);
		feed_info.setOnClickListener(this);

		li = (LineGraph) getActivity().findViewById(R.id.linegraph);

		
		
		//体温和计步器，根据市儿童还是婴儿择一显示
		childtemp=(LinearLayout) getActivity().findViewById(R.id.child_temp);
		childstep=(LinearLayout) getActivity().findViewById(R.id.child_step);

		c_step = (TextView) getActivity().findViewById(R.id.c_step);
		
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		LoginUser user = UserCache.getOauth(getActivity());
		/*if (user != null) {
			changeChildAvatar(false);
		}*/
		
		//加载孩子
		if(user.getChildlist()!=null&&user.getChildlist().size()>0){
			int position=user.childPosition;//当前选中孩子
			Child child = user.getChildlist().get(position);
			child_name.setText(child.getName());
			child_device.setText(child.getDeviceNo());
			imageLoader.displayImage(child.getPath(), avat_main, options);
			
			//根据孩子类型显示视图
			if(child.getCustomerFlag()==1){
				childtemp.setVisibility(View.VISIBLE);
				childstep.setVisibility(View.INVISIBLE);
				//体温
				getTempData(child.getId());
			}else if(child.getCustomerFlag()==2){
				childstep.setVisibility(View.VISIBLE);
				childtemp.setVisibility(View.INVISIBLE);
				//计步器
				getStepData(child.getId());
			}
			
		}
		
	}

	@Override
	public void onClick(View v) {
		Intent it = null;
		switch (v.getId()) {

		case R.id.medication_c:
			it = new Intent(getActivity(), MedicationListActivity.class);
			it.putExtra("type", 1);// 小孩用药记录 1
			startActivity(it);
			break;
		case R.id.child_regiser:
			it = new Intent(getActivity(), ChildRegisterActivity.class);
			startActivity(it);

			break;
		case R.id.feed_info:
			it = new Intent(getActivity(), LactationListActivity.class);
			startActivity(it);
			break;
		case R.id.avat_main:
			// 小孩子主头像的点击事件
			
			it=new Intent(getActivity(), ChildEditActivity.class);
			
			startActivity(it);
			
			break;

		case R.id.headll:
			
			LoginUser user = UserCache.getOauth(getActivity());
			
			if(user.getChildlist()!=null&&user.getChildlist().size()>0){
				Intent in=new Intent(getActivity(), ChildSelectActivity.class);
				getActivity().startActivity(in);
			}
			
			break;
		default:

			break;

		}

	}

	//

/*	*//**
	 * 
	 * @param changed
	 *            第一次加载，还是点击了切换按钮
	 *//*
	private void changeChildAvatar(boolean changed) {
		LoginUser user = UserCache.getOauth(getActivity());
		if (user == null) {
			return;
		}
		ArrayList<Child> childList = user.getChildlist();
		if (childList == null) {
			return;
		}
		int childSize = childList.size();
		int position = user.childPosition;
		int currentPosition = position;
		child = null;
		if (childSize == 0) {
			// 没有小孩子
			avat_change.setVisibility(View.GONE);
			child_name.setText(R.string.no_info);
			top_layout.setVisibility(View.GONE);
			center_layout.setVisibility(View.GONE);
			bottom_layout.setVisibility(View.GONE);

		} else if (childSize == 1) {
			// 一个小孩子
			avat_change.setVisibility(View.GONE);

			top_layout.setVisibility(View.VISIBLE);
			center_layout.setVisibility(View.VISIBLE);
			bottom_layout.setVisibility(View.VISIBLE);

			child = childList.get(0);
			child_name.setText(child.getName());
			child_device.setText(child.getDeviceNo());
			imageLoader.displayImage(child.getPath(), avat_main, options);

		} else if (childSize >= 2) {
			// 两个小孩子

			top_layout.setVisibility(View.VISIBLE);
			center_layout.setVisibility(View.VISIBLE);
			bottom_layout.setVisibility(View.VISIBLE);

			avat_change.setVisibility(View.VISIBLE);
			if (changed) {
				currentPosition = ++position;
				user.childPosition = currentPosition % childSize;
			}
			child = childList.get(currentPosition % childSize);
			Child otherChild = childList.get(currentPosition++ % childSize);
			child_name.setText(child.getName());
			child_device.setText(child.getDeviceNo());

			imageLoader.displayImage(child.getPath(), avat_main, options);
			imageLoader
					.displayImage(otherChild.getPath(), avat_change, options);

		}
		if (child != null) {
			getData(child.getId(), changed);
		}

		// else{
		// //大于两个小孩子
		// avat_change.setVisibility(View.VISIBLE);
		//
		// if(changed){
		// currentPosition= ++position;
		// user.childPosition=currentPosition%childSize;
		// }
		// Child child=childList.get(currentPosition%childSize);
		// Child otherChild=childList.get(currentPosition++%childSize);
		//
		// Log.e("----------------------",
		// "-----"+currentPosition%childSize+"=============="+child.toString());
		// child_name.setText(child.getName());
		// child_device.setText(child.getDeviceNo());
		//
		// }
		UserCache.saveOAuth(user, getActivity());
	}*/
	
	
	
	
	
	
	/**
	 * 获取计步器数据
	 * flag true 母亲  false 儿童
	 * @param customerId
	 */
	private void getStepData(String customerId) {

		Uri.Builder builder = Uri.parse(Constants.GET_MED_SPORT).buildUpon();
		builder.appendQueryParameter("customerId", customerId + "");

		RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
		Log.d("GET_MED_SPORT", "GET_MED_SPORT" + builder.toString());
		JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
				Request.Method.GET, builder.toString(), null,
				new Response.Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject arg0) {

						Log.d("GET_MED_SPORT",
								"GET_MED_SPORT" + arg0.toString());
						try {
							MedPercentAndSportResult a = new Gson().fromJson(
									arg0.toString(),
									MedPercentAndSportResult.class);
							if (a == null) {
								return;
							}
							if (a.isFlag()) {

								MedPercentAndSport result = a.getRows();
								
								//setMotherInfo(result);
								//设置步数
								String step=result.getSteps();
								
								c_step.setText(step);
									
							} else {
								Toast.makeText(getActivity(), a.getMsg() + "",
										Toast.LENGTH_LONG).show();
							}
						} catch (Exception e) {
						}
					}

				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError arg0) {
						
						Toast.makeText(getActivity(),
								getString(R.string.net_error) + "",
								Toast.LENGTH_LONG).show();
					}
				});
		requestQueue.add(jsonObjectRequest);
	}
	
	

	private void getTempData(String customerId) {
		Uri.Builder builder = Uri.parse(Constants.GET_MED_LAC).buildUpon();
		builder.appendQueryParameter("customerId", customerId + "");

		show();

		RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
		Log.d("GET_MED_LAC", "GET_MED_LAC" + builder.toString());
		JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
				Request.Method.GET, builder.toString(), null,
				new Response.Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject arg0) {
						dissMiss();
						Log.d("GET_MED_LAC", "GET_MED_LAC" + arg0.toString());
						try {
							MedAndLacPercentResult a = new Gson().fromJson(
									arg0.toString(),
									MedAndLacPercentResult.class);
							if (a == null) {
								return;
							}
							if (a.isFlag()) {
								setChildDataInfo(a.getRows());

							} else {
								Toast.makeText(getActivity(), a.getMsg() + "",
										Toast.LENGTH_LONG).show();
							}
						} catch (Exception e) {
						}
					}

				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError arg0) {
						dissMiss();
						Toast.makeText(getActivity(),
								getString(R.string.net_error) + "",
								Toast.LENGTH_LONG).show();
					}
				});
		requestQueue.add(jsonObjectRequest);
	}

	private void setChildDataInfo(MedAndLacPercent med) {

		if (med == null) {
			return;
		}
		// 设置体温
		setLine(med.getTemperature());

		try {
			String nextMedDateString = med.getNextMedDate();
			if (nextMedDateString != null) {
				nextMedDate.setText(nextMedDateString);
			}else{
				nextMedDate.setText("");
			}

			String nextLacDateString = med.getNextLacDate();
			if (nextLacDateString != null) {
				nextLacDate.setText(nextLacDateString);
			}else{
				nextLacDate.setText("");
			}
			String lactationNum = med.getLactationTime();
			if (lactationNum != null && lactationNum.length() > 0) {
				lactation_progress.setProgress(Integer.parseInt(lactationNum));
			}else{
				lactation_progress.setProgress(0);
			}

			String medecentNum = med.getMedPecentNum();
			if (medecentNum != null && medecentNum.length() > 0) {
				medecent_progress.setProgress(Integer.parseInt(medecentNum));
			}else{
				medecent_progress.setProgress(0);
			}

		} catch (Exception e) {
		}

	}

	private void setLine(double[] temperature) {
		if (li != null) {
			li.removeAllLines();
		}

		if (temperature == null || temperature.length < 1) {
			//没有提问数据，就默认为5个0 
			temperature = new double[5];
		}
		int size = temperature.length;

		Line l = new Line();

		try {
			// 设置最上面的文字温度
			c_tem.setText(df.format(temperature[0]) + "℃");

			if (size == 1) {
				// 如果返回的体温数据只有一条，重复显示5次
				double t = temperature[0];
				for (int i = 0; i < 5; i++) {
					LinePoint p = new LinePoint();
					p.setX(i);
					p.setY((int)t);
					p.setLabel_string(df.format(t));
					l.addPoint(p);
				}

			} else {
				// 如果返回的体温数据大于5条，只显示最新的5条
				size = size > 5 ? 5 : size;
				for (int i = 0; i < size; i++) {
					double t = temperature[i];
					LinePoint p = new LinePoint();
					p.setX(i);
					p.setY((int)t);
					p.setLabel_string(df.format(t));
					l.addPoint(p);
				}
			}

			l.setColor(getResources().getColor(R.color.comm_pink));
			li.addLine(l);
			li.setLabelSize(20);
			li.setRangeY(0, 40);
			li.setLineToFill(0);

		} catch (NumberFormatException n) {

		}

	}

	/**
	 * 显示进度加载框
	 */
	public void show() {
		if (loadingDialog == null) {
			loadingDialog = LoadingDialog.createDialog(getActivity());
			// 点击外部区域，是否消失loadingDialog
			loadingDialog.setCanceledOnTouchOutside(false);
		}
		loadingDialog.setMessage("正在加载");
		loadingDialog.show();
	}

	/**
	 * 关闭进度加载框
	 */
	public void dissMiss() {
		if (loadingDialog != null) {
			loadingDialog.dismiss();
			loadingDialog = null;
		}
	}

}
